package com.huobi.db;

import javax.sql.DataSource;

import org.apache.ibatis.plugin.Interceptor;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.SqlSessionTemplate;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.core.annotation.Order;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport;

@Configuration
@MapperScan(basePackages = { "com.huobi.db.mapper" }, sqlSessionFactoryRef = "sqlSessionFactoryForMoney")
public class DbConfig {

	/**
	 * 构建sqlSessionFactory
	 * 
	 * @return
	 * @throws Exception
	 */
	@Bean
	@Primary
	@Order(2)
	public SqlSessionFactory sqlSessionFactoryForMoney(DataSource dataSource) throws Exception {
		SqlSessionFactoryBean factoryBean = new SqlSessionFactoryBean();
		PathMatchingResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
		factoryBean.setMapperLocations(resolver.getResources("classpath:mapper/*.xml"));
		factoryBean.setTypeAliasesPackage("com.huobi.db.mapper");
		factoryBean.setDataSource(dataSource);
		factoryBean.setPlugins(new Interceptor[] { new com.github.pagehelper.PageHelper() });
		SqlSessionFactory sqlSessionFactory = factoryBean.getObject();
		org.apache.ibatis.session.Configuration configuration = sqlSessionFactory.getConfiguration();
		configuration.setMapUnderscoreToCamelCase(true);
		return sqlSessionFactory;
	}

	@Bean
	@Primary
	@Order(3)
	public SqlSessionTemplate sqlSessionTemplateForMoney(@Autowired SqlSessionFactory sqlSessionFactory)
			throws Exception {
		return new SqlSessionTemplate(sqlSessionFactory);
	}

}